<template>
  <v-app class="history-page">
    <!-- 顶部工具栏 -->
    <v-app-bar color="surface" elevation="1" flat>
      <v-container
        class="d-flex align-center pa-0"
        :style="{ maxWidth: MAIN_CONTENT_MAX_WIDTH_PX }"
      >
        <v-app-bar-title class="text-h6 font-weight-bold">
          <v-icon class="me-2 text-primary" :icon="mdiHistory" />
          {{ t('history.title') }}
        </v-app-bar-title>

        <v-spacer />

        <!-- 时间范围筛选 -->
        <v-menu>
          <template #activator="{ props }">
            <v-btn
              v-bind="props"
              class="me-2"
              :icon="mdiCalendar"
              :title="t('history.filter.title')"
              variant="text"
            />
          </template>
          <v-list rounded="lg">
            <v-list-item @click="filterByTimeRange('today')">
              <v-list-item-title>{{ t('history.filter.today') }}</v-list-item-title>
            </v-list-item>
            <v-list-item @click="filterByTimeRange('yesterday')">
              <v-list-item-title>{{ t('history.filter.yesterday') }}</v-list-item-title>
            </v-list-item>
            <v-list-item @click="filterByTimeRange('week')">
              <v-list-item-title>{{ t('history.filter.this-week') }}</v-list-item-title>
            </v-list-item>
            <v-list-item @click="filterByTimeRange('month')">
              <v-list-item-title>{{ t('history.filter.this-month') }}</v-list-item-title>
            </v-list-item>
            <v-list-item @click="filterByTimeRange('all')">
              <v-list-item-title>{{ t('history.filter.all-time') }}</v-list-item-title>
            </v-list-item>
          </v-list>
        </v-menu>

        <!-- 搜索框 -->
        <v-text-field
          v-model="searchQuery"
          class="me-4"
          clearable
          hide-details
          :placeholder="t('history.search-placeholder')"
          :prepend-inner-icon="mdiMagnify"
          style="max-width: 320px; min-width: 240px"
          variant="outlined"
          @input="onSearchInput"
        />

        <!-- 操作按钮组 -->
        <div class="d-flex align-center ga-2">
          <!-- 选中项数量显示 -->
          <v-chip v-if="selectedItems.length > 0" color="primary" size="small" variant="tonal">
            {{ t('history.selected-count', { count: selectedItems.length }) }}
          </v-chip>

          <!-- 删除按钮 -->
          <v-btn
            v-if="selectedItems.length > 0"
            color="error"
            :icon="mdiDelete"
            :title="t('history.delete-selected')"
            variant="text"
            @click="showDeleteDialog = true"
          />

          <!-- 全选/取消全选 -->
          <v-btn
            :icon="isAllSelected ? mdiCheckboxMarked : mdiCheckboxBlankOutline"
            :title="isAllSelected ? t('history.unselect-all') : t('history.select-all')"
            variant="text"
            @click="toggleSelectAll"
          />

          <!-- 更多操作菜单 -->
          <v-menu>
            <template #activator="{ props }">
              <v-btn v-bind="props" :icon="mdiDotsVertical" variant="text" />
            </template>
            <v-list rounded="lg">
              <v-list-item @click="showClearAllDialog = true">
                <template #prepend>
                  <v-icon :icon="mdiDeleteSweep" />
                </template>
                <v-list-item-title>{{ t('history.clear-all') }}</v-list-item-title>
              </v-list-item>
            </v-list>
          </v-menu>
        </div>
      </v-container>
    </v-app-bar>

    <!-- 主要内容区域 -->
    <v-main class="flex-grow-1 position-relative">
      <!-- 加载状态 -->
      <v-progress-linear
        v-if="loading"
        class="position-absolute"
        color="primary"
        indeterminate
        style="top: 0; left: 0; right: 0; z-index: 10"
      />

      <!-- 空状态 -->
      <v-container
        v-if="!loading && groupedHistory.length === 0"
        class="d-flex align-center justify-center"
        :style="{ height: 'calc(100vh - 80px)', maxWidth: MAIN_CONTENT_MAX_WIDTH_PX }"
      >
        <v-empty-state
          :icon="mdiHistory"
          :text="t('history.empty-text')"
          :title="t('history.empty-title')"
        />
      </v-container>

      <!-- 历史记录列表 - 使用虚拟滚动作为唯一滚动容器 -->
      <div v-else class="virtual-scroll-container">
        <v-virtual-scroll
          ref="virtualScrollRef"
          class="history-virtual-scroll"
          :item-height="40"
          item-key="id"
          :items="flattenedHistoryItems"
          style="height: calc(100vh - 80px)"
          @scroll="handleScroll"
        >
          <template #default="{ item }">
            <!-- 日期分组标题 -->
            <div v-if="'type' in item && item.type === 'group-header'" class="sticky-header mt-2">
              <div class="group-header-content">
                <span class="group-date-text">{{ formatGroupDate(item.date) }}</span>
                <span class="group-count-text">{{ item.count }} {{ t('history.items') }}</span>
              </div>
            </div>

            <!-- 加载更多指示器 -->
            <v-container
              v-else-if="'type' in item && item.type === 'loading-more'"
              class="pa-0"
              :style="{ maxWidth: MAIN_CONTENT_MAX_WIDTH_PX }"
            >
              <div class="d-flex align-center justify-center pt-2 pb-3">
                <v-progress-circular color="primary" indeterminate size="32" />
                <span class="text-caption ms-2">正在加载更多...</span>
              </div>
            </v-container>

            <!-- 没有更多数据提示 -->
            <v-container
              v-else-if="'type' in item && item.type === 'no-more-data'"
              class="pa-0"
              :style="{ maxWidth: MAIN_CONTENT_MAX_WIDTH_PX }"
            >
              <div class="d-flex align-center justify-center pt-2 pb-3">
                <span class="text-caption text-medium-emphasis">已加载全部历史记录</span>
              </div>
            </v-container>

            <!-- 历史记录项 -->
            <v-container
              v-else-if="'url' in item && item.id !== undefined"
              class="pa-0 px-4"
              :style="{ maxWidth: MAIN_CONTENT_MAX_WIDTH_PX }"
            >
              <HistoryItem
                :item="item"
                :selected="selectedItems.includes(item.id)"
                @delete="deleteItem"
                @toggle-select="toggleItemSelect"
              />
            </v-container>
          </template>
        </v-virtual-scroll>
      </div>
    </v-main>

    <!-- 删除确认对话框 -->
    <v-dialog v-model="showDeleteDialog" max-width="400">
      <v-card>
        <v-card-title>
          <v-icon class="me-2" color="warning" :icon="mdiAlertCircle" />
          {{ t('history.delete-confirm-title') }}
        </v-card-title>
        <v-card-text>
          {{ t('history.delete-confirm-text', { count: selectedItems.length }) }}
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn variant="text" @click="showDeleteDialog = false">
            {{ t('common.cancel') }}
          </v-btn>
          <v-btn color="error" variant="flat" @click="confirmDelete">
            {{ t('common.delete') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 清空所有历史记录确认对话框 -->
    <v-dialog v-model="showClearAllDialog" max-width="400">
      <v-card>
        <v-card-title>
          <v-icon class="me-2" color="error" :icon="mdiAlertCircle" />
          {{ t('history.clear-all-confirm-title') }}
        </v-card-title>
        <v-card-text>
          {{ t('history.clear-all-confirm-text') }}
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn variant="text" @click="showClearAllDialog = false">
            {{ t('common.cancel') }}
          </v-btn>
          <v-btn color="error" variant="flat" @click="confirmClearAll">
            {{ t('history.clear-all') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-app>
</template>

<script lang="ts" setup>
import type { BrowsingHistory } from '~types/browsing-history'
import {
  mdiAlertCircle,
  mdiCalendar,
  mdiCheckboxBlankOutline,
  mdiCheckboxMarked,
  mdiDelete,
  mdiDeleteSweep,
  mdiDotsVertical,
  mdiHistory,
  mdiMagnify
} from '@mdi/js'
import { computed, onMounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { MAIN_CONTENT_MAX_WIDTH_PX } from '~shared/constants/layout'
import { useHistoryData } from '../composables/useHistoryData'
import HistoryItem from './HistoryItem.vue'

const { t, locale } = useI18n()

// 历史记录数据管理
const {
  historyItems,
  loading,
  pagination,
  isLoadingMore,
  loadHistory,
  loadMore,
  deleteHistoryItems,
  searchHistory,
  clearAllHistory,
  getTodayHistory,
  getThisWeekHistory
} = useHistoryData()
// 搜索和筛选
const searchQuery = ref('')
const selectedItems = ref<number[]>([])
const showDeleteDialog = ref(false)
const showClearAllDialog = ref(false)

// 无限滚动状态
const virtualScrollRef = ref()
const isNearBottom = ref(false)
const currentTimeFilter = ref<string>('all')

// 搜索防抖
let searchTimeout: NodeJS.Timeout | null = null
function onSearchInput() {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  searchTimeout = setTimeout(() => {
    if (searchQuery.value.trim()) {
      searchHistory(searchQuery.value.trim())
    } else {
      loadHistory()
    }
  }, 300)
}

// 按天分组历史记录
const groupedHistory = computed(() => {
  const groups: { date: string; items: BrowsingHistory[] }[] = []
  const groupMap = new Map<string, BrowsingHistory[]>()

  for (const item of historyItems.value) {
    const date = new Date(item.visit_time).toDateString()
    if (!groupMap.has(date)) {
      groupMap.set(date, [])
    }
    groupMap.get(date)!.push(item)
  }

  // 按日期降序排列
  const sortedDates = Array.from(groupMap.keys()).sort(
    (a, b) => new Date(b).getTime() - new Date(a).getTime()
  )

  for (const date of sortedDates) {
    groups.push({
      date,
      items: groupMap
        .get(date)!
        .sort((a, b) => new Date(b.visit_time).getTime() - new Date(a.visit_time).getTime())
    })
  }

  return groups
})

// 定义虚拟滚动项类型
type VirtualScrollItem =
  | { type: 'group-header'; date: string; count: number; id: string }
  | { type: 'loading-more'; id: string }
  | { type: 'no-more-data'; id: string }
  | (BrowsingHistory & { id: number })

// 扁平化历史记录项用于虚拟滚动
const flattenedHistoryItems = computed(() => {
  const flattened: VirtualScrollItem[] = []

  for (const group of groupedHistory.value) {
    // 添加分组标题
    flattened.push({
      type: 'group-header',
      date: group.date,
      count: group.items.length,
      id: `header-${group.date}`
    })

    // 添加该分组的所有项目（只添加有id的项目）
    for (const item of group.items) {
      if (item.id !== undefined) {
        flattened.push(item as BrowsingHistory & { id: number })
      }
    }
  }

  // 在末尾添加加载状态项
  if (isLoadingMore.value) {
    flattened.push({ type: 'loading-more', id: 'loading-more' })
  } else if (!pagination.hasMore && flattened.length > 0) {
    flattened.push({ type: 'no-more-data', id: 'no-more-data' })
  }

  return flattened
})

// 格式化分组日期
function formatGroupDate(dateString: string) {
  const date = new Date(dateString)
  const today = new Date()
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)

  if (date.toDateString() === today.toDateString()) {
    return t('history.today')
  } else if (date.toDateString() === yesterday.toDateString()) {
    return t('history.yesterday')
  } else {
    return new Intl.DateTimeFormat(locale.value, {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      weekday: 'long'
    }).format(date)
  }
}

// 全选状态
const isAllSelected = computed(() => {
  const allItemIds = historyItems.value.map(item => item.id!).filter(id => id !== undefined)
  return allItemIds.length > 0 && allItemIds.every(id => selectedItems.value.includes(id))
})

// 切换全选
function toggleSelectAll() {
  selectedItems.value = isAllSelected.value
    ? []
    : historyItems.value.map(item => item.id!).filter(id => id !== undefined)
}

// 切换单项选择
function toggleItemSelect(itemId: number) {
  const index = selectedItems.value.indexOf(itemId)
  if (index === -1) {
    selectedItems.value.push(itemId)
  } else {
    selectedItems.value.splice(index, 1)
  }
}

// 删除单个项目
async function deleteItem(itemId: number) {
  await deleteHistoryItems([itemId])
  selectedItems.value = selectedItems.value.filter(id => id !== itemId)
}

// 确认删除选中项目
async function confirmDelete() {
  // 创建纯数组副本，避免Vue响应式对象序列化问题
  const itemsToDelete = [...selectedItems.value]
  await deleteHistoryItems(itemsToDelete)
  selectedItems.value = []
  showDeleteDialog.value = false
}

// 确认清空所有历史记录
async function confirmClearAll() {
  await clearAllHistory()
  selectedItems.value = []
  showClearAllDialog.value = false
}

// 无限滚动处理
function handleScroll(event: Event) {
  const target = event.target as HTMLElement
  if (!target) return

  const { scrollTop, scrollHeight, clientHeight } = target
  const scrollBottom = scrollHeight - scrollTop - clientHeight

  // 检查是否接近底部（距离底部100px时触发）
  isNearBottom.value = scrollBottom < 100

  // 触发加载更多
  if (isNearBottom.value && pagination.hasMore && !isLoadingMore.value && !loading.value) {
    handleLoadMore()
  }
}

// 加载更多数据
async function handleLoadMore() {
  if (!pagination.hasMore || isLoadingMore.value) return

  try {
    const params = searchQuery.value
      ? {
          title_pattern: searchQuery.value,
          url_pattern: searchQuery.value
        }
      : undefined
    await loadMore(params)
  } catch (error) {
    console.error('加载更多失败:', error)
  }
}

// 按时间范围筛选
async function filterByTimeRange(range: string) {
  currentTimeFilter.value = range
  selectedItems.value = []

  switch (range) {
    case 'today': {
      await getTodayHistory()
      break
    }
    case 'week': {
      await getThisWeekHistory()
      break
    }
    case 'yesterday': {
      const now = new Date()
      const yesterday = new Date(now)
      yesterday.setDate(yesterday.getDate() - 1)
      const startTime = new Date(
        yesterday.getFullYear(),
        yesterday.getMonth(),
        yesterday.getDate()
      ).getTime()
      const endTime = new Date(
        yesterday.getFullYear(),
        yesterday.getMonth(),
        yesterday.getDate() + 1
      ).getTime()

      await (searchQuery.value.trim()
        ? searchHistory(searchQuery.value.trim(), {
            timeRange: { start: startTime, end: endTime }
          })
        : loadHistory({
            start_time: startTime,
            end_time: endTime
          }))
      break
    }
    case 'month': {
      const monthStart = new Date()
      monthStart.setDate(1)
      monthStart.setHours(0, 0, 0, 0)

      await (searchQuery.value.trim()
        ? searchHistory(searchQuery.value.trim(), {
            timeRange: { start: monthStart.getTime() }
          })
        : loadHistory({
            start_time: monthStart.getTime()
          }))
      break
    }
    case 'all':
    default: {
      await (searchQuery.value.trim() ? searchHistory(searchQuery.value.trim()) : loadHistory())
      break
    }
  }
}

// 监听语言变化，重新加载数据以更新日期格式
watch(locale, () => {
  // 触发重新计算分组
})

// 组件挂载时加载数据
onMounted(() => {
  loadHistory()
})
</script>

<i18n>
{
  "en": {
    "history": {
      "title": "History",
      "search-placeholder": "Search history...",
      "empty-title": "No browsing history",
      "empty-text": "Your browsing history will appear here",
      "items": "items",
      "today": "Today",
      "yesterday": "Yesterday",
      "selected-count": "{count} selected",
      "delete-selected": "Delete selected items",
      "select-all": "Select all",
      "unselect-all": "Unselect all",
      "clear-all": "Clear all history",
      "delete-confirm-title": "Delete History Items",
      "delete-confirm-text": "Are you sure you want to delete {count} history item(s)? This action cannot be undone.",
      "clear-all-confirm-title": "Clear All History",
      "clear-all-confirm-text": "Are you sure you want to clear all browsing history? This action cannot be undone.",
      "item": {
        "visited-times": "Visited {count} times"
      },
      "filter": {
        "title": "Filter by time range",
        "today": "Today",
        "yesterday": "Yesterday",
        "this-week": "This week",
        "this-month": "This month",
        "all-time": "All time"
      }
    },
    "common": {
      "cancel": "Cancel",
      "delete": "Delete",
      "confirm": "Confirm"
    }
  },
  "zhHans": {
    "history": {
      "title": "历史记录",
      "search-placeholder": "搜索历史记录...",
      "empty-title": "暂无浏览历史",
      "empty-text": "您的浏览历史将显示在这里",
      "items": "项",
      "today": "今天",
      "yesterday": "昨天",
      "selected-count": "已选择 {count} 项",
      "delete-selected": "删除选中项",
      "select-all": "全选",
      "unselect-all": "取消全选",
      "clear-all": "清空所有历史记录",
      "delete-confirm-title": "删除历史记录",
      "delete-confirm-text": "确定要删除 {count} 条历史记录吗？此操作无法撤销。",
      "clear-all-confirm-title": "清空所有历史记录",
      "clear-all-confirm-text": "确定要清空所有浏览历史记录吗？此操作无法撤销。",
      "item": {
        "visited-times": "访问了 {count} 次"
      },
      "filter": {
        "title": "按时间范围筛选",
        "today": "今天",
        "yesterday": "昨天",
        "this-week": "本周",
        "this-month": "本月",
        "all-time": "全部时间"
      }
    },
    "common": {
      "cancel": "取消",
      "delete": "删除",
      "confirm": "确认"
    }
  }
}
</i18n>

<style scoped>
/* 只保留必要的自定义样式，最大化使用Vuetify工具类 */

.history-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 粘性定位的日期分组标题 */
.sticky-header {
  height: 32px;
  display: flex;
  align-items: center;
}

.group-header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  max-width: v-bind(MAIN_CONTENT_MAX_WIDTH_PX);
  margin: 0 auto;
  padding: 0 20px;
}

.group-date-text {
  font-size: 0.875rem;
  font-weight: 600;
  color: rgb(var(--v-theme-primary));
}

.group-count-text {
  font-size: 0.75rem;
  color: rgb(var(--v-theme-on-surface));
  opacity: 0.7;
}

/* 深色主题下的粘性标题 */
.v-theme--dark .sticky-header {
  background-color: rgb(var(--v-theme-background));
  border-bottom-color: rgba(var(--v-theme-outline), 0.2);
}

/* 虚拟滚动容器样式 */
.virtual-scroll-container {
  position: relative;
  height: calc(100vh - 80px);
}

.history-virtual-scroll {
  /* 确保虚拟滚动容器是唯一的滚动区域 */
  overflow-y: auto;
  overflow-x: hidden;
  height: 100%;
}
</style>
